//
//  StrategyController.m
//  FreeTrip
//
//  Created by 邓芮 on 15/11/25.
//  Copyright © 2015年 邓芮. All rights reserved.
//

#import "StrategyController.h"
#import "StrategyHeaderView.h"
#import "StrategyCell.h"
#import "StrategyModel.h"
#import "StrategyDetailController.h"
@interface StrategyController ()<UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) NSMutableArray *modelArray;

@end

static NSString *headerIdentifier = @"cell";
@implementation StrategyController

static NSString * const reuseIdentifier = @"Cell";
//- (NSMutableArray *)modelArray
//{
//    if (!_modelArray)
//    {
//        self.modelArray = [NSMutableArray array];
//    }
//    return _modelArray;
//}
- (void)loadView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    CGFloat width = (KScreenWidth - 30 * KScreenWidth / 414) / 2;
    CGFloat height = 30 * KScreenWidth / 414;
    layout.itemSize = CGSizeMake(width, height);
    
    UICollectionView *collectView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
    collectView.backgroundColor = [UIColor whiteColor];
    self.collectionView = collectView;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Register cell classes
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
    
    [self.collectionView registerClass:[StrategyHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerIdentifier];
    
    [self.collectionView registerClass:[StrategyCell class] forCellWithReuseIdentifier:reuseIdentifier];
    
    self.navigationItem.title = self.name;
    if ([[NetworkState shareInstance]reachablity])
    {
        [self requestForRaiWithUrl:[NSString stringWithFormat:@"http://chanyouji.com/api/wiki/destinations/%ld.json", (long)self.Id]];
    }
    else
    {
        
        if ([self isHaveFilePath])
        {
           
            NSString *newPath = [self isHaveFilePath];
            
            NSData *aData = [NSData dataWithContentsOfFile:newPath];
            NSArray *array = [NSJSONSerialization JSONObjectWithData:aData options:0 error:nil];
            self.modelArray = [NSMutableArray array];
            for (NSDictionary *firstDic in array)
            {
                NSNumber * category_type = firstDic[@"category_type"];
                NSInteger category = [category_type integerValue];
                
                NSMutableArray *firArray = [NSMutableArray array];
                for (NSDictionary *secDic in firstDic[@"pages"])
                {
                    StrategyModel *model = [[StrategyModel alloc] init];
                    model.category_type = category;
                    [model setValuesForKeysWithDictionary:secDic];
                    
                    [firArray addObject:model];
                    
                }
                [_modelArray addObject:firArray];
            }

            
            
        }
                 
    }
    
    
    
    
//    //下拉刷新
//    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        // 进入刷新状态后会自动调用这个block
//         [self requestForRaiWithUrl:[NSString stringWithFormat:@"http://chanyouji.com/api/wiki/destinations/%ld.json", (long)self.Id]];
//        [self.collectionView.mj_header endRefreshing];
//    }];
}


#pragma mark ---设置缓存----
// 设置文件名
- (NSString *)newFilePath
{
    return [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject] stringByAppendingPathComponent:@"strategy"];
}
// 创建文件
- (NSString *)createNewPath
{
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:[self newFilePath]])
    {
        // 创建文件夹
        [manager createDirectoryAtPath:[self newFilePath] withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    // 在文件夹下创建以id 命名的文档 用来下面存储数组;
    NSString *newPath = [[self newFilePath]stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.plist",self.Id]];
    if (![manager fileExistsAtPath:newPath])
    {
        [manager createFileAtPath:newPath contents:nil attributes:nil];
    }
    return newPath;
    

}

- (NSString *)isHaveFilePath
{
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:[self newFilePath]])
    {
        NSString *newPath = [[self newFilePath]stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.plist",self.Id]];
        if ([manager fileExistsAtPath:newPath])
        {
            return newPath;
        }
        else
        {
            return NO;
        }

       
    }else
    {
        return NO;
    }
    
    
    
}

#pragma mark ---strategy请求00----
- (void)requestForRaiWithUrl:(NSString *)url
{
    
    [[NetworkState shareInstance]reachablityStates:self];
   
    self.modelArray = [NSMutableArray array];
    [[[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:url] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
      {
          if (data == nil)
          {
              NSLog(@"数据请求失败");
              [MBProgressHUD hideHUDForView:self.view animated:YES];
              return ;
          }
          
          NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
          
#pragma mark ---开始持久化----
          NSString *newPath = [self createNewPath]
          ;
        //  NSLog(@"%@",newPath);
       [data writeToFile:newPath atomically:YES];
         
      
          for (NSDictionary *firstDic in array)
          {
              NSNumber * category_type = firstDic[@"category_type"];
              NSInteger category = [category_type integerValue];
              
              NSMutableArray *firArray = [NSMutableArray array];
              for (NSDictionary *secDic in firstDic[@"pages"])
              {
                  StrategyModel *model = [[StrategyModel alloc] init];
                  model.category_type = category;
                  [model setValuesForKeysWithDictionary:secDic];
                  
                  [firArray addObject:model];
                  
              }
              [_modelArray addObject:firArray];
          }
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [self.collectionView reloadData];
        });
        
        
    }] resume];
    
}



#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
//    if (self.modelArray.count != 0)
//    {
//        return self.modelArray.count;
//    }
//    return 0;]
    return self.modelArray.count;
    
    
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [self.modelArray[section] count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    StrategyCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    
    NSMutableArray *array = self.modelArray[indexPath.section];
    StrategyModel *model = array[indexPath.item];
    cell.model = model;
    return cell;
}

#pragma mark -- header --
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    StrategyHeaderView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headerIdentifier forIndexPath:indexPath];
    NSMutableArray *array = self.modelArray[indexPath.section];
    StrategyModel *model = array[indexPath.item];
    header.model = model;
    
    return header;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(KScreenWidth, 50 * KScreenWidth / 414);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((KScreenWidth - 50 * KScreenWidth / 414) / 2, 30 * KScreenWidth / 414);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    CGFloat ww = 10 * KScreenWidth / 414;
    return UIEdgeInsetsMake(0, ww, ww, ww);
}


#pragma mark -- 详情跳转 --
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    StrategyDetailController *strategyDetailVc = [[StrategyDetailController alloc]init];
    StrategyModel *model = self.modelArray[indexPath.section][indexPath.row];
    strategyDetailVc.array = model.children;
    [self.navigationController pushViewController:strategyDetailVc animated:NO];
}

#pragma mark <UICollectionViewDelegate>

/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
	return YES;
}
*/

/*
// Uncomment this method to specify if the specified item should be selected
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
*/

/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
- (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath {
	return NO;
}

- (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	return NO;
}

- (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	
}
*/

@end
